<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Serial Port Communication</title>
</head>
<body>
    <button onclick="connectSerial()">Connect to Serial Port</button>
    <textarea id="serialData" rows="10" cols="40"></textarea>
    <video id="videoPlayer" width="640" height="360" controls>
        Your browser does not support the video tag.
    </video>

    <script>
        let videoPlayer = document.getElementById('videoPlayer');

        async function connectSerial() {
            try {
                const port = await navigator.serial.requestPort();
                await port.open({ baudRate: 9600 });

                const reader = port.readable.getReader();
                while (true) {
                    const { value, done } = await reader.read();
                    if (done) {
                        break;
                    }

                    const receivedData = new TextDecoder().decode(value);
                    document.getElementById('serialData').value += receivedData;

                    // 根据接收到的数据播放或暂停视频
                    handleSerialData(receivedData.trim());
                }
            } catch (error) {
                console.error('Error connecting to serial port:', error);
            }
        }

        function handleSerialData(data) {
            if (data === '1') {
                playVideo();
            } else if (data === '0') {
                pauseVideo();
            }
        }

        function playVideo() {
            if (!videoPlayer.src) {
                videoPlayer.src = '1.mp4'; // 设置默认视频文件路径
            }
            videoPlayer.play();
        }

        function pauseVideo() {
            videoPlayer.pause();
        }
    </script>
</body>
</html>